package com.quanshu.shop.order;

import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.support.constraint.ConstraintLayout;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.ImageView;
import android.widget.TextView;

import com.gyf.barlibrary.ImmersionBar;
import com.quanshu.exchange.R;
import com.quanshu.exchange.support.net.BaseResponse;
import com.quanshu.exchange.support.net.core.BaseObserver;
import com.quanshu.exchange.support.net.core.BaseTransformer;
import com.quanshu.exchange.support.net.core.NetClient;
import com.quanshu.exchange.support.utils.RxViewHelper;
import com.quanshu.exchange.support.utils.ToastHelper;
import com.quanshu.exchange.ui.base.BaseActivity;
import com.quanshu.shop.base.data.BroadcastReciverAction;
import com.quanshu.shop.base.tool.BaseTool;
import com.quanshu.shop.base.view.BaseTitleBar;
import com.quanshu.shop.goods.entity.CartBaseEntity;
import com.quanshu.shop.main.api.ShopMainIF;
import com.quanshu.shop.order.adapter.SubmitOrderAdapter;
import com.quanshu.shop.order.custom.InsufficientBanlance1Dialog;
import com.quanshu.shop.order.custom.InsufficientBanlanceDialog;
import com.quanshu.shop.order.entity.CreatOrderEntity;
import com.quanshu.shop.order.entity.MyBalanceEntity;
import com.quanshu.shop.order.entity.SubmitOrderViewEntity;
import com.quanshu.shop.order.entity.SubmitPrepareEntity;
import com.quanshu.shop.pay.PayCashActivity;
import com.quanshu.shop.pay.PayNjfActivity;
import com.quanshu.shop.person.entity.MySelectAddressEntity;
import com.quanshu.shop.person.view.AddAddressActivity;
import com.quanshu.shop.person.view.SelectMyAddressActivity;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;

public class SubmitOrderActivity extends BaseActivity implements InsufficientBanlanceDialog.OnInsufficientBanlanceListener {
    @BindView(R.id.submit_order_title)
    BaseTitleBar submitOrderTitle;
    @BindView(R.id.submit_order_address1_img)
    ImageView submitOrderAddress1Img;
    @BindView(R.id.submit_order_address1)
    ConstraintLayout submitOrderAddress1;
    @BindView(R.id.submit_order_address2_img)
    ImageView submitOrderAddress2Img;
    @BindView(R.id.submit_order_address2_br)
    View submitOrderAddress2Br;
    @BindView(R.id.submit_order_address2_txt1)
    TextView submitOrderAddress2Txt1;
    @BindView(R.id.submit_order_address2_txt2)
    TextView submitOrderAddress2Txt2;
    @BindView(R.id.submit_order_address2_txt3)
    TextView submitOrderAddress2Txt3;
    @BindView(R.id.submit_order_address2_img1)
    ImageView submitOrderAddress2Img1;
    @BindView(R.id.submit_order_address2)
    ConstraintLayout submitOrderAddress2;
    @BindView(R.id.submit_order_address)
    ConstraintLayout submitOrderAddress;
    @BindView(R.id.submit_order_rl)
    RecyclerView submitOrderRl;
    @BindView(R.id.submit_order_sv)
    NestedScrollView submitOrderSv;
    @BindView(R.id.cart_foot_txt1)
    TextView cartFootTxt1;
    @BindView(R.id.cart_foot_txt2)
    TextView cartFootTxt2;
    @BindView(R.id.cart_foot_txt3)
    TextView cartFootTxt3;
    @BindView(R.id.cart_foot_txt4)
    TextView cartFootTxt4;
    @BindView(R.id.cart_foot_cl1)
    ConstraintLayout cartFootCl1;
    @BindView(R.id.cart_foot_cl2)
    TextView cartFootCl2;
    @BindView(R.id.submit_order_foot)
    ConstraintLayout submitOrderFoot;
    private String orderId = "";
    private int mOrderState = 0;//0代表购物车 1代表直接购买
    private List<CartBaseEntity> cartBaseEntityList;
    private List<SubmitOrderViewEntity> submitOrderViewEntityList;//生成预订单，前面页面带过来的数据
    private SubmitOrderAdapter submitOrderAdapter;
    private SubmitPrepareEntity.AddressListEntity addressListEntity;
    private InsufficientBanlanceDialog insufficientBanlanceDialog;
    private InsufficientBanlance1Dialog insufficientBanlance1Dialog;
    private SubmitPrepareEntity submitPrepareEntityResult;
    private boolean isPay = false;
    private String payAway;
    private Context mContext;
    private boolean isRefresh = false;
    private String addressId = "";
    public static final String CREATE_ORDER = "create_order";
    private String getStringID = null;
    private String goodsType = "";


    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == SelectMyAddressActivity.RESULT_DATA) {
            if (data.getExtras() != null && data.getExtras().getSerializable("my_select_address") != null) {
                addressListEntity = (SubmitPrepareEntity.AddressListEntity) data.getExtras().getSerializable("my_select_address");
                submitOrderAddress2Txt1.setText("收货人：" + addressListEntity.getAccept_name());
                submitOrderAddress2Txt2.setText(addressListEntity.getMobile());
                submitOrderAddress2Txt3.setText("收货地址：" + addressListEntity.getProvince_val() + addressListEntity.getCity_val() + addressListEntity.getArea_val() + addressListEntity.getAddress());
                addressId = addressListEntity.getId();
                getPrepareOrder();
            } else {
                submitOrderAddress1.setVisibility(View.VISIBLE);
                submitOrderAddress2.setVisibility(View.GONE);
            }
        } else if (requestCode == AddAddressActivity.ADDRESS_RESULT_CODE) {
            //没有地址删光了
            if (data.getExtras() != null && data.getExtras().getSerializable("result_data") != null) {
                MySelectAddressEntity mySelectAddressEntity = (MySelectAddressEntity) data.getExtras().getSerializable("result_data");
                addressListEntity = mySelectAddressEntity.getAddressListEntity();
                submitOrderAddress2Txt1.setText("收货人：" + addressListEntity.getAccept_name());
                submitOrderAddress2Txt2.setText(addressListEntity.getMobile());
                submitOrderAddress2Txt3.setText("收货地址：" + addressListEntity.getProvince_val() + addressListEntity.getCity_val() + addressListEntity.getArea_val() + addressListEntity.getAddress());
                addressId = addressListEntity.getId();
                getPrepareOrder();
            }
        }
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_submit_order);
        ButterKnife.bind(this);
        mContext = this;
        initView();
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        ImmersionBar.with(this).destroy();
    }

    private void initView() {
        ImmersionBar.with(this).statusBarColor("#FFFFFF").statusBarDarkFont(true).titleBar(submitOrderTitle).init();
        insufficientBanlanceDialog = new InsufficientBanlanceDialog(this).setOnDeleteAddressListener(this);
        insufficientBanlance1Dialog = new InsufficientBanlance1Dialog(this).setOnDeleteAddressListener(this);
        RxViewHelper.getInstance().clicks(submitOrderAddress1, aVoid ->
                {
                    Bundle bundle = new Bundle();
                    bundle.putString("title", "添加地址");
                    bundle.putString("request_code", String.valueOf(SelectMyAddressActivity.ADD_ADDRESS));
                    Intent intent = new Intent();
                    intent.setClass(SubmitOrderActivity.this, AddAddressActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, AddAddressActivity.ADDRESS_RESULT_CODE);
                }

        );
        RxViewHelper.getInstance().clicks(submitOrderAddress2, aVoid ->
                {
                    Bundle bundle = new Bundle();
                    bundle.putSerializable("my_select_address", addressListEntity);
                    Intent intent = new Intent();
                    intent.setClass(SubmitOrderActivity.this, SelectMyAddressActivity.class);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, SelectMyAddressActivity.RESULT_DATA);
                }

        );
        //订单结算
        RxViewHelper.getInstance().clicks(cartFootCl2, aVoid ->
                {
                    //BaseTool.goActivity(mContext, PayNjfActivity.class, null);
                    if (submitPrepareEntityResult == null) {
                        ToastHelper.toast("预订单生成失败！");
                        getPrepareOrder();
                    } else {
                        //判断是否需要牛积分支付
                        if (isPay) {//可以进行下单
                            creatOrder();
                        } else {
                            if (Double.parseDouble(submitPrepareEntityResult.getNiuScore_sum()) > 0) {
                                getMyBalance();
                            } else {
                                //生成订单 正常支付
                                payAway = "0";
                                creatOrder();
                            }
                        }

                    }
                }
        );
        submitOrderTitle.setLeftImage(R.drawable.icon_back_black_2_0).setCenterText("订单结算").setOnClickBaseTitleListener(new BaseTitleBar.OnClickBaseTitleBarListener() {
            @Override
            public void onclickLeft() {
                finish();
            }

            @Override
            public void onclickRight() {

            }
        });
        submitOrderViewEntityList = new ArrayList<>();
        Bundle bundle = getIntent().getExtras();
        LinearLayoutManager linearLayoutManager = new LinearLayoutManager(this);
        linearLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        submitOrderRl.setLayoutManager(linearLayoutManager);
        //submitOrderRl.setHasFixedSize(true);
        submitOrderRl.setNestedScrollingEnabled(false);
        if (bundle != null) {
            mOrderState = Integer.parseInt(bundle.getString("order_state"));
            getStringID = bundle.getString("address_id");
            orderId = bundle.getString("order_id");
            cartBaseEntityList = (List<CartBaseEntity>) bundle.getSerializable("order_data");
            Log.d("提交订单", "initView: " + cartBaseEntityList.size());
        } else {
            return;
        }
        if (cartBaseEntityList != null && cartBaseEntityList.size() > 0) {
            for (int a = 0; a < cartBaseEntityList.size(); a++) {
                SubmitOrderViewEntity submitOrderViewEntity = new SubmitOrderViewEntity();
                submitOrderViewEntity.setCartBaseEntity(cartBaseEntityList.get(a));
                submitOrderViewEntityList.add(submitOrderViewEntity);
            }
            getPrepareOrder();
        }


    }

    //生成预订单
    private void getPrepareOrder() {
        StringBuilder goodsArrBuilder = new StringBuilder();
        if (submitOrderViewEntityList != null && submitOrderViewEntityList.size() > 0) {
            for (int a = 0; a < submitOrderViewEntityList.size(); a++) {
                if (TextUtils.isEmpty(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getSpec_array())) {
                    Log.d("结算1", "getPrepareOrder: " + submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getGoods_id());
                    goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getGoods_id());
                    goodsArrBuilder.append(",");
                    goodsArrBuilder.append("goods");
                } else {
                    goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getProduct_id());
                    goodsArrBuilder.append(",");
                    goodsArrBuilder.append("product");
                }
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getCount());
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getIs_service());
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getPayment_options());
                goodsArrBuilder.append("&");
            }
        } else {
            return;
        }
        Log.d("上传", "getPrepareOrder: " + goodsArrBuilder.toString());
        goodsArrBuilder.delete(goodsArrBuilder.length() - 1, goodsArrBuilder.length());
        String arr = goodsArrBuilder.toString();
        NetClient.getInstance().getShopService(ShopMainIF.class)
                .getPrepareOrder(currentUser.getId(), arr, currentUser.getMemberid(), addressId, "0")
                .compose(new BaseTransformer<>(this, true, false)).subscribe(new BaseObserver<BaseResponse<SubmitPrepareEntity>>() {
            @Override
            public void onSuccess(BaseResponse<SubmitPrepareEntity> response) {
                submitPrepareEntityResult = response.getData();
                if (!isRefresh) {
                    submitOrderAdapter = new SubmitOrderAdapter(submitPrepareEntityResult.getGoodsList(), mContext, new SubmitOrderAdapter.GetEditWordsListenner() {
                        @Override
                        public void getEditData(String s, int position) {
                            submitPrepareEntityResult.getGoodsList().get(position).setWords(s);
                            submitOrderViewEntityList.get(position).setWords(s);
                            Log.d("填写第" + position + "个留言", "getEditData: " + s);
                        }
                    });
                    submitOrderRl.setAdapter(submitOrderAdapter);
                    isRefresh = true;
                } else {
                    submitOrderAdapter.setNewData(response.getData().getGoodsList());
                }
                BigDecimal bigDecimalMoney1 = new BigDecimal(response.getData().getFinal_sum());
                BigDecimal bigDecimalFreight = new BigDecimal(response.getData().getPriceFreight());
                BigDecimal bigDecimalMoney2 = new BigDecimal(response.getData().getNiuScore_sum());
                BigDecimal bigDecimalFreight1 = new BigDecimal(response.getData().getNiuFreight());
                if (bigDecimalMoney1.doubleValue() > 0 && bigDecimalMoney2.doubleValue() > 0) {
                    cartFootTxt2.setVisibility(View.VISIBLE);
                    cartFootTxt3.setVisibility(View.VISIBLE);
                    cartFootTxt4.setVisibility(View.VISIBLE);
                } else if (bigDecimalMoney1.doubleValue() > 0) {
                    cartFootTxt2.setVisibility(View.VISIBLE);
                    cartFootTxt3.setVisibility(View.GONE);
                    cartFootTxt4.setVisibility(View.GONE);
                } else if (bigDecimalMoney2.doubleValue() > 0) {
                    cartFootTxt2.setVisibility(View.GONE);
                    cartFootTxt3.setVisibility(View.GONE);
                    cartFootTxt4.setVisibility(View.VISIBLE);
                } else {
                    cartFootTxt2.setVisibility(View.GONE);
                    cartFootTxt3.setVisibility(View.GONE);
                    cartFootTxt4.setVisibility(View.GONE);
                }
                cartFootTxt2.setText(bigDecimalMoney1.add(bigDecimalFreight).toString());
                cartFootTxt4.setText(bigDecimalMoney2.add(bigDecimalFreight1).toString());
                if (response.getData().getAddressList() != null && response.getData().getAddressList().size() > 0) {
                    submitOrderAddress1.setVisibility(View.GONE);
                    submitOrderAddress2.setVisibility(View.VISIBLE);
                    for (int a = 0; a < response.getData().getAddressList().size(); a++) {
                        if (getStringID != null) {
                            if (getStringID.equals(response.getData().getAddressList().get(a).getId())) {
                                submitOrderAddress2Txt1.setText("收货人：" + response.getData().getAddressList().get(a).getAccept_name());
                                submitOrderAddress2Txt2.setText(response.getData().getAddressList().get(a).getMobile());
                                submitOrderAddress2Txt3.setText("收货地址：" + response.getData().getAddressList().get(a).getProvince_val() + response.getData().getAddressList().get(a).getCity_val() + response.getData().getAddressList().get(a).getArea_val() + response.getData().getAddressList().get(a).getAddress());
                                addressListEntity = response.getData().getAddressList().get(a);
                                addressId = addressListEntity.getId();
                            }
                        } else {
                            if (Integer.parseInt(response.getData().getAddressList().get(a).getIs_default()) == 1) {
                                submitOrderAddress2Txt1.setText("收货人：" + response.getData().getAddressList().get(a).getAccept_name());
                                submitOrderAddress2Txt2.setText(response.getData().getAddressList().get(a).getMobile());
                                submitOrderAddress2Txt3.setText("收货地址：" + response.getData().getAddressList().get(a).getProvince_val() + response.getData().getAddressList().get(a).getCity_val() + response.getData().getAddressList().get(a).getArea_val() + response.getData().getAddressList().get(a).getAddress());
                                addressListEntity = response.getData().getAddressList().get(a);
                                addressId = addressListEntity.getId();
                            } else {
                                submitOrderAddress2Txt1.setText("收货人：" + response.getData().getAddressList().get(0).getAccept_name());
                                submitOrderAddress2Txt2.setText(response.getData().getAddressList().get(0).getMobile());
                                submitOrderAddress2Txt3.setText("收货地址：" + response.getData().getAddressList().get(0).getProvince_val() + response.getData().getAddressList().get(0).getCity_val() + response.getData().getAddressList().get(0).getArea_val() + response.getData().getAddressList().get(0).getAddress());
                                addressListEntity = response.getData().getAddressList().get(0);
                                addressId = addressListEntity.getId();
                            }
                        }

                    }
                } else {
                    submitOrderAddress1.setVisibility(View.VISIBLE);
                    submitOrderAddress2.setVisibility(View.GONE);
                }
            }
        });
    }

    //创建订单
    private void creatOrder() {
        StringBuilder goodsArrBuilder = new StringBuilder();
        StringBuilder remarkWords = new StringBuilder();
        if (submitOrderViewEntityList != null && submitOrderViewEntityList.size() > 0) {
            for (int a = 0; a < submitOrderViewEntityList.size(); a++) {
                remarkWords.append(submitOrderViewEntityList.get(a).getWords());
                remarkWords.append(",");
                if (TextUtils.isEmpty(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getSpec_array())) {
                    goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getGoods_id());
                    goodsArrBuilder.append(",");
                    goodsArrBuilder.append("goods");
                } else {
                    goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getProduct_id());
                    goodsArrBuilder.append(",");
                    goodsArrBuilder.append("product");
                }
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getCount());
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getIs_service());
                goodsArrBuilder.append(",");
                goodsArrBuilder.append(submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().getPayment_options());
                goodsArrBuilder.append("&");
            }
            Log.d("留言：", "creatOrder: " + remarkWords.toString());
        } else {
            return;
        }
        Log.d("创建订单", "getPrepareOrder: " + goodsArrBuilder.toString());
        goodsArrBuilder.delete(goodsArrBuilder.length() - 1, goodsArrBuilder.length());
        if (goodsArrBuilder.length() > 0) {
            remarkWords.delete(remarkWords.length() - 1, remarkWords.length());
        }
        String arr = goodsArrBuilder.toString();

        NetClient.getInstance().getShopService(ShopMainIF.class)
                .createOrder(currentUser.getId(), arr, currentUser.getMemberid(), addressListEntity.getId(), orderId, remarkWords.toString())
                .compose(new BaseTransformer<>(this, true, false)).subscribe(new BaseObserver<BaseResponse<CreatOrderEntity>>() {
            @Override
            public void onSuccess(BaseResponse<CreatOrderEntity> response) {
                Bundle bundle = new Bundle();
                bundle.putSerializable(CREATE_ORDER, response.getData());
                Intent intent = new Intent();
                intent.setAction(BroadcastReciverAction.UPDATE_MY_CART);
                sendBroadcast(intent);
                if (Double.parseDouble(response.getData().getNiuScore_sum()) <= 0) {
                    //跳转到现金支付界面
                    BaseTool.goActivity(mContext, PayCashActivity.class, bundle);
                    finish();
                } else {
                    //跳转到牛积分支付界面
                    BaseTool.goActivity(mContext, PayNjfActivity.class, bundle);
                    finish();
                }
            }
        });
    }

    private void getMyBalance() {
        NetClient.getInstance().getShopService(ShopMainIF.class).getMyBalance(currentUser.getId())
                .compose(new BaseTransformer<>(this)).subscribe(new BaseObserver<BaseResponse<MyBalanceEntity>>() {
            @Override
            public void onSuccess(BaseResponse<MyBalanceEntity> response) {
                if (Double.parseDouble(submitPrepareEntityResult.getNiuScore_sum()) > response.getData().getNiupoint()) {
                    if (Double.parseDouble(submitPrepareEntityResult.getFinal_sum()) > 0) {
                        insufficientBanlanceDialog.show();
                    } else {
                        insufficientBanlance1Dialog.show();
                    }

                } else {
                    //创建订单
                    payAway = "0";
                    creatOrder();
                }
            }
        });
    }

    @Override
    public void payAllMoney() {
        Log.d("现金支付全部订单", "payAllMoney: ");
        for (int a = 0; a < submitOrderViewEntityList.size(); a++) {
            submitOrderViewEntityList.get(a).getCartBaseEntity().getGoodsListEntity().setPayment_options("0");
        }
        getPrepareOrder();
        isPay = true;
        payAway = "1";
    }

    @Override
    public void payPartMoney() {
        Log.d("仅支付现金订单", "payPartMoney: ");
        if (Double.parseDouble(submitPrepareEntityResult.getFinal_sum()) > 0) {
            Iterator iterator = submitOrderViewEntityList.iterator();
            while (iterator.hasNext()) {
                SubmitOrderViewEntity submitOrderViewEntity = (SubmitOrderViewEntity) iterator.next();
                if (Integer.parseInt(submitOrderViewEntity.getCartBaseEntity().getGoodsListEntity().getPayment_options()) == 1) {
                    iterator.remove();
                }
            }
            getPrepareOrder();
            isPay = true;
            payAway = "2";
        }
    }
}
